﻿using System.Windows.Controls;
using System.Windows.Interactivity;
using System.Windows.Data;

namespace Ops.Mpc.Behaviors
{
    /// <summary>
    /// This behavior causes text box controls to update thier text property bindings as soon as the text is changed in them.
    /// Using this beavior on a textbox allows model validation rules to execute as users types.
    /// </summary>
    public class TextBoxTextChangedBindingBehavior : Behavior<TextBox>
    {
        #region Methods
        protected override void OnAttached()
        {
            base.OnAttached();
            this.AssociatedObject.TextChanged += new TextChangedEventHandler(OnTextChanged);
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();
            this.AssociatedObject.TextChanged -= new TextChangedEventHandler(OnTextChanged);
        }

        private void OnTextChanged(object sender, TextChangedEventArgs e)
        {
            BindingExpression bindingExpression = this.AssociatedObject.GetBindingExpression(TextBox.TextProperty);
            bindingExpression.UpdateSource();
        }
        #endregion
    }
}
